<?php
/**
 * Created by PhpStorm.
 * User: TS
 * Date: 2017/4/4
 * Time: 20:25
 */
namespace core;

class Config {

    protected static $instance = null;

    protected static $configs = [];

    /**
     * @return null|static
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 获取某个配置的值
     * @param $name
     * @return bool|mixed
     */
    public static function get($name = '')
    {
        return empty($name) ? self::$configs : (self::has($name) ? self::$configs[$name] : false);
    }

    /**
     * @param $name
     * @return bool
     */
    public static function has($name)
    {
        return isset(self::$configs[$name]);
    }

    /**
     * 加载配置文件 相对conf 文件下的路径
     * @param $file
     * @param $root_path
     * @return bool|mixed
     */
    public static function load($file, $root_path = ROOT_PATH . 'conf/')
    {
        static $includes = [];

        $basePath = $root_path . $file;

        if (!file_exists($basePath)) return false;
        $uuid = md5($basePath. 'conf');
        if (!isset($includes[$uuid]) && is_file($basePath)) {
            $includes[$uuid] = include $basePath . '';
            self::$configs = array_merge(self::$configs, (array)$includes[$uuid]);
        }

        return isset($includes[$uuid]) ? $includes[$uuid] : false;
    }

    /**
     * 加载模块配置文件
     * @param string $module
     * @return bool
     */
    public static function loadModuleConfig($module = 'common')
    {
        if (!$module) return false;

        $path = ROOT_PATH . 'conf/' . $module . '/';

        if (!is_dir($path)) return false;

        if (!empty($files = glob($path . '*.php'))) {
            foreach ($files as $file) {
                //文件名的全路径 包含文件名
                self::load($file, '');
            }

            return true;
        }
        return false;
    }
}